package auth

import (
	"admin/dao/auth"
	dto "admin/dto"
	"admin/modules/auth/logic"
	"admin/utils"
	"admin/utils/response"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
	"strconv"
)

type MenuController struct {
	menuLogic *logic.MenuLogic
}

func NewMenuController(db *gorm.DB) *MenuController {
	menuRepo := auth.NewMenuRepo(db)
	return &MenuController{
		menuLogic: logic.NewMenuLogic(menuRepo),
	}
}

// List 获取菜单列表
func (menu *MenuController) List(c *gin.Context) {
	list, err := menu.menuLogic.List()
	if err != nil {
		response.Error(c, http.StatusInternalServerError, 5001, err.Error(), "获取列表失败")
		return
	}
	response.OK(c, gin.H{"list": list}, "success", "成功")
}

// GetMenuTree 获取菜单树
func (menu *MenuController) GetMenuTree(c *gin.Context) {
	menuList, err := menu.menuLogic.GetMenuTree()
	if err != nil {
		response.Error(c, http.StatusInternalServerError, 5001, err.Error(), "获取菜单树失败")
		return
	}
	response.OK(c, gin.H{"list": menuList}, "success", "成功")
}

// Create 创建菜单
func (menu *MenuController) Create(c *gin.Context) {
	req, _ := utils.BindJson[dto.CreateMenuReq](c)
	if err := menu.menuLogic.Create(req.Name, req.ParentID, req.Path, req.Icon, req.Sort, req.Visible); err != nil {
		response.Error(c, http.StatusBadRequest, 1002, err.Error(), "创建失败")
		return
	}
	response.OK(c, nil, "created", "创建成功")
}

// Update 更新菜单
func (menu *MenuController) Update(c *gin.Context) {
	id, _ := strconv.ParseInt(c.Param("id"), 10, 64)
	req, _ := utils.BindJson[dto.UpdateMenuReq](c)
	if err := menu.menuLogic.Update(id, req.ParentID, req.Name, req.Path, req.Icon, req.Sort, req.Visible); err != nil {
		response.Error(c, http.StatusBadRequest, 1002, err.Error(), "更新失败")
		return
	}
}

// Delete 删除菜单
func (menu *MenuController) Delete(c *gin.Context) {
	id, _ := strconv.ParseInt(c.Param("id"), 10, 64)
	if err := menu.menuLogic.Delete(id); err != nil {
		response.Error(c, http.StatusBadRequest, 1002, err.Error(), "删除失败")
	}
}

// GetMenuByID 根据ID获取菜单
func (menu *MenuController) GetMenuByID(c *gin.Context) {
	id, _ := strconv.ParseInt(c.Param("id"), 10, 64)
	menuInfo, err := menu.menuLogic.GetMenuByID(id)
	if err != nil {
		response.Error(c, http.StatusBadRequest, 1002, err.Error(), "获取失败")
	}
	response.OK(c, gin.H{"menu": menuInfo}, "success", "成功")
}
